package com.app.controller.backstage;

import com.app.common.Result;
import com.app.mapper.AdminUserMapper;
import com.app.mapper.OpenidMapper;
import com.app.model.*;
import com.app.service.AdminUserService;
import com.app.service.ComplaintService;
import com.app.service.RoleService;
import com.app.service.UserService;
import com.app.util.CommonHelp;
import com.app.util.TokenUtils;
import com.app.vo.ComplainVo;
import com.app.vo.UserVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static org.apache.commons.codec.digest.DigestUtils.md5Hex;

@RestController
@Controller
@RequestMapping("/szwq")
public class UserBehindController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private ComplaintService complaintService;
    @Autowired
    private OpenidMapper openidMapper;
    @Autowired
    private RoleService roleService;
    /**
     * 查询用户列表
     *
     * @param request
     * @return
     */
    @GetMapping("/getBehindUserList")
    public Result<Object> getBehindUserList(HttpServletRequest request, Integer page, Integer limit, String keyWord) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        page = (page - 1) * limit;
        List<UserModel> userModels = userService.selectAll(page, limit, keyWord);
//        for (int i = 0; i < userModels.size(); i++) {
//            List<ComplaintModel> complaintModels = complaintService.selectByUserId(userModels.get(i).getId());
//            userModels.get(i).setComplaintModel(complaintModels);
//        }
        int count = userService.selectCount(keyWord);
        UserVo vo = new UserVo();
        vo.setList(userModels);
        vo.setCount(count);
        return Result.success(vo);
    }

    /**
     * 用户数据编辑
     *
     * @param model
     * @param request
     * @return
     */
    @PostMapping("/editBehindUser")
    public Result<Object> editBehindUser(
            @RequestBody UserModel model,
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        userService.updateUserInfo(model);
        return Result.success("操作成功");
    }


    /**
     * 用户详情
     *
     * @param request
     * @return
     */
    @GetMapping("/getBehindUser")
    public Result<Object> getBehindUser(
            HttpServletRequest request, Integer id, Integer page, Integer limit) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        List<ComplaintModel> complaintModels = complaintService.selectByUserId(id);
        List<ComplaintModel> collect = complaintModels.stream().skip((long) (page - 1) * limit).limit(limit).collect(Collectors.toList());
        ComplainVo vo = new ComplainVo();
        vo.setList(collect);
        vo.setCount(complaintModels.size());
        return Result.success(vo);
    }

    /**
     * 根据ID查询用户
     *
     * @param request
     * @return
     */
    @GetMapping("/getBehindUserById")
    public Result<Object> getBehindUserById(
            HttpServletRequest request, Integer id) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        UserModel userModel = userService.selectUserById(id);
        return Result.success(userModel);
    }

    //给权限
    @GetMapping("/givePermissions")
    public Result<Object> givePermissions(
            HttpServletRequest request, Integer id, Integer status) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (userId.equals("false")) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        UserModel userModel = userService.selectUserById(id);
        //授权
        if (status != null && status == 2) {
            userModel.setStatus(status);
            userService.updateUserInfo(userModel);
            OpenidModel model = new OpenidModel();
            model.setOpenid(userModel.getOpenid());
            model.setName(userModel.getUserName());
            model.setMobile(userModel.getMobile());
            openidMapper.insert(model);
            //生成管理员账号  密码默认 mswq_手机号后四位
            String salt = "dh_wq";
            String mobile = userModel.getMobile();
            String substring = mobile.substring(mobile.length() - 4);
            String password = "mswq_" + substring;
            String newWord = md5Hex(password + salt);
            AdminUserModel adminUserModel = new AdminUserModel();
            adminUserModel.setAccount(userModel.getMobile());
            adminUserModel.setRealName(userModel.getUserName());
            adminUserModel.setPassword(newWord);
            adminUserModel.setRoles(2);
            RoleModel roleModel = roleService.getRoleByRoleId(adminUserModel.getRoles());
            adminUserModel.setRoleName(roleModel.getRoleName());
            adminUserModel.setStatus(1);
            adminUserModel.setUserId(id);
            adminUserModel.setMobile(userModel.getMobile());
            adminUserModel.setCreateTime(CommonHelp.getNowTimestamp());
            adminUserService.insertAdmin(adminUserModel);
        }
        //取消授权
        if (status != null && status == 1) {
            userModel.setStatus(status);
            userService.updateUserInfo(userModel);
            QueryWrapper<OpenidModel> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("mobile", userModel.getMobile());
            OpenidModel model = openidMapper.selectOne(queryWrapper);
            openidMapper.deleteById(model.getId());
            QueryWrapper<AdminUserModel> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("account", userModel.getMobile());
            AdminUserModel adminUserModel = adminUserMapper.selectOne(queryWrapper1);
            adminUserMapper.deleteById(adminUserModel.getId());
        }
        return Result.success("操作成功");
    }
}
